﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using mmCore.Common;
using mmCore.Interfaces;

namespace mmSubProvider
{
    public class SubSearch: ISearchable<SubSearchResult>
    {
        #region EVENTS

        public event Action<List<SubSearchResult>> OnFound;
        public event Action<SubSearchResult> OnSearchProgress;

        #endregion EVENTS

        #region MEMBERS

        private int _mSearchMoviesNum;
        private List<SubSearchResult> _mSearchResult;

        #endregion MEMBERS

        #region METHODS

        public bool Search(string searchString)
        {
            if (string.IsNullOrEmpty(searchString))
            {
                return false;
            }

            _mSearchMoviesNum = 0;
            _mSearchResult = new List<SubSearchResult>();

            var wf = new WebFetch(
                SubUtils.MovieSearchUrl,
                new List<Tuple<string, string>>
                    {
                        new Tuple<string, string>("q", searchString)
                    });
            wf.OnFinished += OnSearchFinished;
            wf.Fetch();

            return true;
        }

        #endregion METHODS

        #region PRIVATE

        private void OnSearchFinished(object sender, FetchEventArgs e)
        {
            const string strRegex = "<a href=\"/tvshow-([\\d\\D]*?).html\">";

            var rRegex = new Regex(strRegex, RegexOptions.Multiline);
            var mMatch = rRegex.Match(e.Result);

            while (mMatch.Success)
            {
                var nMovieId = mMatch.Groups[1].Value;
                var wf = new WebFetch(SubUtils.GetMovieUrl(nMovieId, 1));
                wf.OnFinished += OnSubSearchFinished;
                Interlocked.Increment(ref _mSearchMoviesNum);
                wf.Fetch(nMovieId);
                mMatch = mMatch.NextMatch();
            }

            while (_mSearchMoviesNum > 0)
            {
                Thread.Sleep(200);
            }
            if (OnFound != null)
            {
                OnFound(_mSearchResult);
            }
        }

        private void OnSubSearchFinished(object sender, FetchEventArgs e)
        {
            const string strRegex = "<h2>([\\d\\D]*?)</h2>";
            var rr = new Regex(strRegex);
            var mm = rr.Match(e.Result);

            var strTitle = string.Empty;

            if (mm.Success)
            {
                strTitle = mm.Groups[1].Value;
            }

            var strRegexSeasons = string.Format("<a href=\"tvshow-{0}-([\\d]*?).html\">", e.Data);
            rr = new Regex(strRegexSeasons);
            mm = rr.Match(e.Result);

            var maxSeason = 0;

            while (mm.Success)
            {
                var season = Int32.Parse(mm.Groups[1].Value);
                if (season > maxSeason)
                {
                    maxSeason = season;
                }
                mm = mm.NextMatch();
            }

            var newMovie = new SubSearchResult
            {
                Title = strTitle,
                SeasonCount = maxSeason,
                Id = e.Data.ToString(),
            };

            if (OnSearchProgress != null) OnSearchProgress(newMovie);
            lock (_mSearchResult)
            {
                _mSearchResult.Add(newMovie);
            }

            Interlocked.Decrement(ref _mSearchMoviesNum);
        }

        #endregion PRIVATE
    }
}
